package com.ct.ah.lab.service.impl;

import com.ct.ah.lab.dao.OrderDao;
import com.ct.ah.lab.dao.OrderItemDao;
import com.ct.ah.lab.entity.Address;
import com.ct.ah.lab.entity.Order;
import com.ct.ah.lab.entity.OrderItem;
import com.ct.ah.lab.entity.User;
import com.ct.ah.lab.entity.vo.CartVo;
import com.ct.ah.lab.service.*;
import com.ct.ah.lab.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("OrderService")
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderItemDao orderItemDao;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICartService cartService;

    @Autowired
    private IPointService pointService;
    @Autowired
    private ICashService cashService;

    //保存订单后返回订单id
    @Override
    public Integer save(Integer aid, List<Integer> cids, String infoParam, User user) {
        //生成订单商品列表，顺便计算总价
        List<OrderItem> orderItems = new ArrayList<>();
        List<CartVo> cartVos = cartService.listCartByCids(cids);
        double totalPricse = 0;

        //处理infoParam数据，获取是否开发票、留言信息
        Map<String, HashMap<String, String>> info = new HashMap();
        if (infoParam != null) {
            String[] split = infoParam.split(",");
            for (int i = 0; i < split.length; i++) {
                HashMap map = new HashMap<String, String>();
                String[] value = split[i].split("-");
                map.put("msg", value[1]);
                map.put("bill", value[2]);
                info.put(value[0], map);
            }
        }
        for (CartVo vo : cartVos
        ) {
            OrderItem orderItem = new OrderItem();
            orderItem.setPid(vo.getPid());
            orderItem.setNum(vo.getNum());
            orderItem.setPrice(vo.getRealPrice());
            orderItem.setImage(vo.getImage());
            orderItem.setTitle(vo.getTitle());
            if (info.get(vo.getPid().toString()).get("msg") != null) {
                orderItem.setMsg(info.get(vo.getPid().toString()).get("msg"));
            }
            orderItem.setBill(Integer.parseInt(info.get(vo.getPid().toString()).get("bill")));
            orderItems.add(orderItem);
            totalPricse += vo.getRealPrice() * vo.getNum();
            cartService.removeByCid(vo.getCid());
        }

        Address address = addressService.getByAid(aid);
        Order order = new Order();
        order.setUid(user.getUid());
        order.setCreatedUser(user.getUsername());
        order.setPrice(totalPricse);
        order.setRecvAddress(address.getAddress());
        order.setRecvArea(address.getAreaName());
        order.setRecvCity(address.getCityName());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        //手动设置订单状态，0为待付款，1未超时未付款，2已付款
        order.setStatus(0);
        String orderCode = OrderUtil.getOrderCode(user.getUid());
        order.setOrderCode(orderCode);
        orderDao.save(order);

        Integer orderId = order.getId();

        for (OrderItem orderItem : orderItems
        ) {
            orderItem.setCreatedUser(user.getUsername());
            orderItem.setOid(orderId);
            orderItemDao.save(orderItem);
        }
        return orderId;

    }

    @Override
    public List<Order> list(Integer uid) {
        //格式化时间工具
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

        List<Order> orders = orderDao.getByUid(uid);
        for (Order order : orders
        ) {
            List<OrderItem> byOid = orderItemDao.getByOid(order.getId());
            for (OrderItem o :
                    byOid) {
                o.setCreatedTimes(sdf.format(o.getCreatedTime()));
                System.out.println(o.getCreatedTimes());
            }
            order.setOrderItems(byOid);
        }
        return orders;
    }

    @Override
    public List<Order> listByStatus(Integer uid, Integer status) {
        //格式化时间工具
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

        HashMap<String, Integer> map = new HashMap();
        map.put("uid", uid);
        map.put("status", status);
        List<Order> orders = orderDao.getByUidAndStatus(map);
        for (Order order : orders
        ) {
            List<OrderItem> byOid = orderItemDao.getByOid(order.getId());
            for (OrderItem o :
                    byOid) {
                o.setCreatedTimes(sdf.format(o.getCreatedTime()));
            }
            order.setOrderItems(byOid);
        }
        return orders;
    }


    @Override
    public Order getbyOid(Integer oid) {
        //格式化时间工具
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        Order order = orderDao.getByOid(oid);
        if (order!=null) {
            List<OrderItem> byOid = orderItemDao.getByOid(order.getId());
            for (OrderItem o :
                    byOid) {
                o.setCreatedTimes(sdf.format(o.getCreatedTime()));
            }
            order.setOrderItems(byOid);
        }
        return order;
    }

    @Override
    public void changeStatus(Integer oid, Integer status, Integer payStyle, User user) {
        Order order = orderDao.getByOid(oid);
        if (order != null) {
            order.setStatus(status);
            order.setPayStyle(payStyle);
            order.setModifiedUser(user.getUsername());
            orderDao.updateStatus(order);
        }
    }

    @Override
    public void returnOrder(Integer oid, User user) {
        //积分回退，获取当前账单信息
        Order returnOrder = orderDao.getByOid(oid);
        //获取当前账单支付方式，现金支付，则更改钱包，积分支付则更改积分
        Integer payStyle = returnOrder.getPayStyle();
        //判断
        if (payStyle == 2) {
            //积分支付，进行回滚
            pointService.reducePoint(oid, user);
        } else {
            //花钱支付，对账户进行回滚进行回滚
            cashService.returnByCash(oid, user);
        }
    }

}
